import { createStore } from 'vuex'

export default createStore({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    sidebar: {
      opened: true
    },
    settings: {
      theme: localStorage.getItem('theme') || 'light',
      language: localStorage.getItem('language') || 'zh-CN'
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    TOGGLE_SIDEBAR(state) {
      state.sidebar.opened = !state.sidebar.opened
    },
    SET_SETTINGS(state, { key, value }) {
      state.settings[key] = value
      localStorage.setItem(key, value)
    },
    LOGOUT(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  },
  actions: {
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        // 这里可以添加实际的登录API调用
        // 模拟登录成功
        setTimeout(() => {
          const token = 'admin-token'
          const userInfo = {
            id: 1,
            username: 'admin',
            name: '管理员',
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            roles: ['admin']
          }
          commit('SET_TOKEN', token)
          commit('SET_USER_INFO', userInfo)
          resolve()
        }, 1000)
      })
    },
    logout({ commit }) {
      commit('LOGOUT')
    },
    toggleSidebar({ commit }) {
      commit('TOGGLE_SIDEBAR')
    },
    updateSettings({ commit }, data) {
      commit('SET_SETTINGS', data)
    }
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    sidebar: state => state.sidebar,
    settings: state => state.settings
  }
})